"""
get_h3c_pool_all_iops_wr()函数负责调用华三存储api，得到集群iops数据，将查询结果传入max_iops()函数进行排序，返回最大的iops值


返回值
[{'target': 'big_cluster.pool.all.iops.rd', 'datapoints': [[0.0, 1719891810], [0.0, 1719891820], [1.0, 1719891830], [0.0, 1719891840], [0.0, 1719891850], [0.0, 1719891860], [2.0, 1719891870], [2.0, 1719891880], [1.0, 1719891890], [0.0, 1719891900], [0.0, 1719891910], [1.0, 1719891920], [6.0, 1719891930], [10.0, 1719891940], [8.0, 1719891950], [2.0, 1719891960], [0.0, 1719891970], [0.0, 1719891980], [4.0, 1719891990], [3.0, 1719892000], [1.0, 1719892010], [0.0, 1719892020], [0.0, 1719892030], [1.0, 1719892040], [0.0, 1719892050], [1.0, 1719892060], [0.0, 1719892070], [0.0, 1719892080], [1.0, 1719892090], [1.0, 1719892100], [41.0, 1719892110]]}]
"""
# -*- coding:utf-8 -*-


import requests
import datetime
import logging
import json
import re

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s : %(levelname)s : %(message)s',
    filename="/var/log/test_storage_api_log/storage_iops_api.log"
)


# 提取当前时间，整理格式后返回当前时间值，用于生成result_txt
def result_txt_time():
    now = datetime.datetime.now()
    now_time = now.strftime("%Y%m%d")
    return now_time


# 调用华三集群的API，获取集群存储读IOPS
def get_h3c_pool_all_iops_wr():
    # 拼接成登陆url
    base_url = "http://地址/"
    request_url = "api/v1/auth/login"
    url = base_url + request_url

    # 登陆用户名、密码
    data = {"username": "xx", "password": "xx"}

    # 登录请求
    res = requests.post(url=url, data=json.dumps(data), headers={'content-type': "application/json"})

    # 从响应头信息中提取后面访问需要的XSRF-TOKEN和calamari_sessionid
    XSRF_TOKEN = res.cookies.get_dict().get('XSRF-TOKEN')
    calamari_sessionid = res.cookies.get_dict().get('calamari_sessionid')
    Cookie = 'XSRF-TOKEN=' + XSRF_TOKEN + ';' + 'calamari_sessionid=' + calamari_sessionid

    # 获取集群ID
    cluster_id_api_url = "/api/v3/plat/cluster"
    cluster_id_url = base_url + cluster_id_api_url
    cluster_res = requests.get(
        url=cluster_id_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': XSRF_TOKEN,
            'Cookie': Cookie,
        })

    cluster_data = cluster_res.json()
    cluster_id = cluster_data['data']['id']

    # 生成请求URL
    # 【请求示例】
    # http://10.10.10.131/graphite/render?format=json&from=-5minute&target=big_cluster.pool.all.iops.rd
    cluster_pool_all_iops_rd_url_1 = "graphite/render"
    cluster_pool_all_iops_rd_url_2 = "?format=json&from=-5minute&target=big_cluster.pool.all.iops.wr"
    cluster_pool_all_iops_rd_url = base_url + cluster_pool_all_iops_rd_url_1 + cluster_pool_all_iops_rd_url_2

    # 发送GET请求，得到返回数据
    # 【响应示例】
    # [
    #     {
    #         "target": " big_cluster.pool.all.iops.rd",
    #         "datapoints": [
    #             [0.0, 1542108120],
    #             [0.0, 1542108150],
    #             [0.0, 1542108180],
    #             [0.0, 1542108210],
    #             [0.0, 1542108240],
    #             [0.0, 1542108270],
    #             [0.0, 1542108300],
    #             [0.0, 1542108330],
    #             [0.0, 1542108360],
    #             [0.0, 1542108390],
    #             [0.0, 1542108420]
    #         ]
    #     }
    # ]
    cluster_pool_all_iops_rd_res = requests.get(
        url=cluster_pool_all_iops_rd_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': XSRF_TOKEN,
            'Cookie': Cookie,
        })
    cluster_pool_all_iops_rd_data = cluster_pool_all_iops_rd_res.json()

    # 生成日志，记录整理后准备发送的数据
    result_txt_name = "/var/log/test_storage_api_log/h3c_iops_log_" + result_txt_time() + ".txt"
    now = datetime.datetime.now()
    now_time = now.strftime("%Y-%m-%d %H:%M")
    with open(result_txt_name, "a") as log:
        try:
            log.write(now_time + ', ' + str(cluster_pool_all_iops_rd_data[0]))
            log.write('\n')
            logging.info("execute write cluster_pool_all_iops_wr_data successful")
        except:
            log.write("error\n")
            logging.error("execute write cluster_pool_all_iops_wr_data error")

    # logout登出
    logout_api_url = "/api/v1/auth/logout"
    logout_url = base_url + logout_api_url
    logout_res = requests.get(
        url=logout_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': XSRF_TOKEN,
            'Cookie': Cookie,
        })
    return cluster_pool_all_iops_rd_data[0]['datapoints']


def max_iops(iops_array=[[0]]):
    # iops_array = [[393.0, 1719892500], [268.0, 1719892510], [177.0, 1719892520], [367.0, 1719892530], [356.0, 1719892540], [143.0, 1719892550], [129.0, 1719892560], [85.0, 1719892570], [99.0, 1719892580], [112.0, 1719892590], [45.0, 1719892600], [5.0, 1719892610], [40.0, 1719892620], [63.0, 1719892630], [42.0, 1719892640], [33.0, 1719892650], [124.0, 1719892660], [73.0, 1719892670], [129.0, 1719892680], [193.0, 1719892690], [130.0, 1719892700], [98.0, 1719892710], [68.0, 1719892720], [14.0, 1719892730], [40.0, 1719892740], [44.0, 1719892750], [26.0, 1719892760], [22.0, 1719892770], [15.0, 1719892780], [51.0, 1719892790], [93.0, 1719892800]]
    # print(sorted(iops_array, reverse=True))
    max_iops_value = sorted(iops_array, reverse=True)[0][0]
    print(max_iops_value)
    return max_iops_value


if __name__ == '__main__':
    h3c_xd_iops_list_data = get_h3c_pool_all_iops_wr()
    max_iops(h3c_xd_iops_list_data)
